package com.ruoyi.web.controller.tuike;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.tiktok.domain.Task;
import com.ruoyi.tiktok.domain.vo.LaunchAppSchema;
import com.ruoyi.tiktok.service.TaskService;
import com.ruoyi.tiktok.service.TikTokService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/tasks")
public class TaskController extends BaseController {
    @Autowired
    private TaskService taskService;
    @Autowired
    private TikTokService tikTokService;
    @PostMapping("/createTask")
    public AjaxResult createTask(@RequestBody @Validated Task task) {
        return taskService.createTask(task);
    }

    @PutMapping("/updateTask")
    public AjaxResult updateTask(@RequestBody Task task) {
        int ins = taskService.updateTask(task);
        return ins==1 ? success():error();
    }

    /**
     * 获取用户列表
     */
    @GetMapping("/getTaskList")
    public TableDataInfo list(Task tasks)
    {
        startPage();
        List<?> list = taskService.selectTaskList(tasks);
        return getDataTable(list);
    }

    /**
     * 导出distribute列表
     */
    //@PreAuthorize("@ss.hasPermi('video-distribute:tasks:export')")
    @Log(title = "distribute", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Task tasks)
    {
        List<Task> list = (List<Task>) taskService.selectTaskList(tasks);
        ExcelUtil<Task> util = new ExcelUtil(Task.class);
        util.exportExcel(response, list, "distribute数据");
    }

    /**
     * 获取distribute详细信息
     * 公开的方法
     */
    @Log(title = "task-distribute", businessType = BusinessType.GRANT ,anonymousUser = "customer")
    @GetMapping(value = "/{taskId}")
    public AjaxResult getInfo(@PathVariable("taskId") String taskId)
    {
        Task task = taskService.selectTasksByTaskId(taskId);

        if(task == null){
            return error("活动不存在/或已经取消");
        }
        Integer status =Integer.valueOf(task.getTaskStatus());
        if(status == 1){
            return  error("活动已经结束了");
        }

       if( status == 0) {
            LaunchAppSchema appSchema  = tikTokService.generateSchemaObj(task);
            return appSchema==null ? error("拉去信息失败"): success(appSchema);
        }

       return error("出错了");
    }


    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody Task task) {
        int No = taskService.changeTaskStatus(task);
        return No >=1?AjaxResult.success():AjaxResult.error();
    }
}

